/*
 * @Author: your name
 * @Date: 2020-06-06 17:32:14
 * @LastEditTime: 2020-10-03 10:31:50
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \crm\lib\main.dart
 */

import 'dart:io';
// import 'package:amap_location/amap_location.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart' hide Router;
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:woniutaofang/pages/index_page.dart';
import 'package:woniutaofang/provider/city.dart';
import 'package:woniutaofang/provider/currentIndex.dart';
import 'package:woniutaofang/provider/houselist/goods_page_provider.dart';
import 'package:woniutaofang/provider/theme_provider.dart';
import 'package:woniutaofang/provider/token/token_provider.dart';
import 'package:woniutaofang/routers/application.dart';
import 'package:woniutaofang/routers/routers.dart';
import 'package:woniutaofang/utils/sp_util.dart';

import 'common/common.dart';
import 'generated/i18n.dart';
import 'package:woniutaofang/utils/config.dart';

Future<void> main() async {
  Config.env = Env.LOCAL;
  WidgetsFlutterBinding.ensureInitialized();
  await SpUtil.getInstance();
  await SpUtil.putInt(Constant.platformLaunch, 3);
  await SpUtil.putInt(Constant.platform, 1);
  await SpUtil.putString(Constant.aid, '10000002');
  await SpUtil.putString(Constant.City, '320100');
  // await AmapService.init(
  //     androidKey: '4e707385edf6030282f06eee8b41b13c',
  //     iosKey: '4e707385edf6030282f06eee8b41b13c');
  if (Platform.isAndroid) {
    // 以下两行 设置android状态栏为透明的沉浸。写在组件渲染之后，是为了在渲染后进行set赋值，覆盖状态栏，写在渲染之前MaterialApp组件会覆盖掉这个值。
    SystemUiOverlayStyle systemUiOverlayStyle =
        SystemUiOverlayStyle(statusBarColor: Colors.transparent);
    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
  }
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (context) => CurrentIndexProvider(),
        ),
        ChangeNotifierProvider(
          create: (context) => ThemeProvider(),
        ),
        ChangeNotifierProvider(
          create: (context) => GoodsPageProvider(),
        ),
        ChangeNotifierProvider(
          create: (context) => CityProvider(),
        ),
        ChangeNotifierProvider(
          create: (context) => TokenProvider(),
        )
      ],
      child: MyApp(),
    ),
  );
}

class MyApp extends StatefulWidget {
  MyApp({Key key, this.theme}) : super(key: key);
  final ThemeData theme;
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  double longitude = 0.0;
  double latitude = 0.0;
  String city;
  @override
  void initState() {
    super.initState();
    SchedulerBinding.instance.addPostFrameCallback((callback) {
      // 设置EasyRefresh的默认样式
      EasyRefresh.defaultHeader = ClassicalHeader(
          enableInfiniteRefresh: false,
          refreshText: '拉动刷新',
          refreshReadyText: '释放刷新',
          refreshingText: '正在刷新...',
          refreshedText: '刷新完成',
          refreshFailedText: '刷新失败',
          noMoreText: '没有更多数据',
          textColor: Colors.grey,
          infoText: '更新于 %T');
      EasyRefresh.defaultFooter = ClassicalFooter(
          enableInfiniteLoad: true,
          loadText: '拉动加载',
          loadReadyText: '释放加载',
          loadingText: '加载中...',
          loadedText: '加载完成',
          loadFailedText: '加载失败',
          noMoreText: '没有更多数据',
          textColor: Colors.grey,
          infoText: '更新于 %T');
    });
    // checkPersmission();
    // Provider.of<ThemeProvider>(context, listen: false)
    //     .setTheme(ThemeMode.dark); // 开启暗黑模式
    // Provider.of<ThemeProvider>(context, listen: false)
    //     .setTheme(ThemeMode.system); //跟随系统
    // Provider.of<ThemeProvider>(context, listen: false)
    //     .setTheme(ThemeMode.light); //关闭暗黑模式
    // _getLocation();
  }

  // void checkPersmission() async {
  //   // 申请权限
  //   print('申请权限');
  //   Map<PermissionGroup, PermissionStatus> permissions =
  //       await PermissionHandler()
  //           .requestPermissions([PermissionGroup.location]);
  //   // 申请结果
  //   PermissionStatus permission = await PermissionHandler()
  //       .checkPermissionStatus(PermissionGroup.location);
  //   if (permission == PermissionStatus.granted) {
  //     print('权限已经打开');
  //     _getLocation();
  //   } else {
  //     bool isOpened = await PermissionHandler().openAppSettings(); //打开应用设置
  //     print('打开应用设置');
  //     print(isOpened);
  //     _getLocation();
  //   }
  // }

  // Future _getLocation() async {
  //   //启动一下
  //   await AMapLocationClient.startup(new AMapLocationOption(
  //       desiredAccuracy: CLLocationAccuracy.kCLLocationAccuracyBest));
  //   //获取地理位置（直接定位）
  //   var result = await AMapLocationClient.getLocation(true);
  //   longitude = result.longitude; //经度
  //   latitude = result.latitude; //纬度
  //   city = result.city;
  //   Provider.of<CityProvider>(context, listen: false).setcity(city);
  //   print(Provider.of<CityProvider>(context, listen: false).getcity());
  // }

  @override
  void dispose() {
    //停止监听定位、销毁定位
    // AMapLocationClient.stopLocation();
    // AMapLocationClient.shutdown();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // final router = Router();
    // Routers.configureRouter(router);
    // Application.router = router;
    final Router router = Router();
    Routes.configureRoutes(router);
    Application.router = router;
    return Selector<ThemeProvider, ThemeProvider>(
      selector: (context, provider) => provider,
      shouldRebuild: (pre, next) => true,
      builder: (context, value, child) {
        print(value.getThemeMode());
        return MaterialApp(
          // theme: ThemeData.dark() ,//暗黑模式
          theme: widget.theme ?? value.getTheme(),
          darkTheme: value.getTheme(isDarkMode: true),
          themeMode: value.getThemeMode(),
          title: "张远涛",
          debugShowCheckedModeBanner: false,
          onGenerateRoute: Application.router.generator,
          // theme: ThemeData(
          //   primaryColor: Colors.blue, // 全局修复TextField光标无法与提示文本对齐问题
          //   // textTheme: TextTheme(
          //   //   subhead: TextStyle(textBaseline: TextBaseline.alphabetic),
          //   // ),
          // ),
          home: IndexPage(),

          /// localizationsDelegates 列表中的元素时生成本地化集合的工厂
          localizationsDelegates: [
            // 为Material Components库提供本地化的字符串和其他值
            GlobalMaterialLocalizations.delegate,

            // 定义widget默认的文本方向，从左往右或从右往左
            GlobalWidgetsLocalizations.delegate,

            S.delegate,

            /// 解决 ‘使用CupertinoAlertDialog 报 'alertDialogLabel' was called on null’ 的BUG
            // const FallbackCupertinoLocalisationsDelegate(),
          ],

          ///
          supportedLocales: S.delegate.supportedLocales,

          ///
          // locale: mapLocales[SupportLocale.values[state.localIndex]],

          /// 不存对应locale时，默认取值Locale('zh', 'CN')
          localeResolutionCallback: S.delegate.resolution(
            fallback: const Locale('zh', 'CN'),
          ),
        );
      },
    );
  }
}
